package com.hx.annotation.di;

import java.lang.reflect.Field;

/**
 * @author jxlgcmh
 * @date 2020-08-16 20:06
 * @description
 */
public class SimpleContainer {
    public static <T> T getInstance(Class<T> clazz) {
        try {
            // 创建
            T instance = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                // 如果有 SimpleInject 注解
                if (field.isAnnotationPresent(SimpleInject.class)) {
                    // 设置为可见
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    Class<?> type = field.getType();
                    // 递归调用  给对应的实例赋值
                    field.set(instance, getInstance(type));
                }
            }
            return instance;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}
